const { Controller } = require("egg");

class TopicMaterialController extends Controller {

  async list() {
    const { topicId } = this.ctx.query;
    if (!topicId) {
      return this.ctx.helper.error("参数异常：缺少topicId");
    }
    try {
      const materials = await this.service.topicMaterial.list(topicId);
      if (!materials) {
        return this.ctx.helper.error("该专题下无材料");
      }
      this.ctx.helper.success(materials);
    } catch (error) {
      this.ctx.helper.error("查询材料列表失败：" + error.message);
    }
  }

  async create() {
    const { ctx, service } = this;
    const { topicId, title, link } = ctx.request.body;

    if (!topicId || !title || !link) {
      return this.ctx.helper.error("topicId、title或link不能为空");
    }
    const topic = await this.service.topic.id(topicId);
    if (!topic) {
      return this.ctx.helper.error("该专题不存在");
    }
    try {
      const result = await service.topicMaterial.create({
        topicId, title, link
      });
      this.ctx.helper.success(result, "材料创建成功");
    } catch (error) {
      this.ctx.helper.error("创建材料失败：" + error.message);
    }
  }

  async delete() {
    const { ctx, service } = this;
    const { id } = ctx.request.body;

    if (!id) {
      return this.ctx.helper.error("参数异常：缺少材料ID");
    }
    try {
      const result = await service.topicMaterial.delete(id);
      if (result === null) {
        return this.ctx.helper.error("材料不存在");
      }
      this.ctx.helper.success(result, "材料删除成功");
    } catch (error) {
      this.ctx.helper.error("删除材料失败：" + error.message);
    }
  }

  async update() {
    const { ctx, service } = this;
    const { id, title, link } = ctx.request.body;

    if (!id) {
      return this.ctx.helper.error("参数异常：缺少材料ID");
    }
    try {
      const result = await service.topicMaterial.update(id, { title, link });
      if (result[0] === 0) {
        return this.ctx.helper.error("更新失败，材料可能不存在");
      }
      this.ctx.helper.success(result, "材料更新成功");
    } catch (error) {
      this.ctx.helper.error("更新材料失败：" + error.message);
    }
  }

}

module.exports = TopicMaterialController;